
var app = angular.module("MainApp", [
    "ui.router",
    "ui.calendar",
    "ui.bootstrap", 
    "oc.lazyLoad",  
    "ngSanitize",
    "ngMessages",
    "ui.select",
    "ngTable",
    "angularFileUpload",
    "ng-echarts",
    "angular-json-editor",
    "jcs-autoValidate",
    "ecList",
    "angular.filter",
    "csModule",
    "csField"
]); 

/* Configure ocLazyLoader(refer: https://github.com/ocombe/ocLazyLoad) */
app.config(['$ocLazyLoadProvider', function ($ocLazyLoadProvider) {
    $ocLazyLoadProvider.config({
        cssFilesInsertBefore: 'ng_load_plugins_before' // load the above css files before a LINK element with this ID. Dynamic CSS files must be loaded between core and theme css files
    });
}]);


////AngularJS v1.3.x workaround for old style controller declarition in HTML
//app.config(['$controllerProvider', function ($controllerProvider) {
//  // this option might be handy for migrating old apps, but please don't use it
//  // in new ones!
//  $controllerProvider.allowGlobals();
//}]);

/* Setup global settings */
app.factory('settings', ['$rootScope', '$http', '$filter', '$location', '$modal', '$window', '$ocLazyLoad', '$timeout', 'validator', 'dataSource', '$q', function ($rootScope, $http, $filter, $location, $modal, $window, $ocLazyLoad, $timeout, validator, dataSource, $q) {
    // supported languages
    var settings = {
        layout: {
            pageSidebarClosed: false, // sidebar menu state
            pageContentWhite: true, // set page content layout
            pageBodySolid: false, // solid body color state
            pageAutoScrollOnLoad: 1000 // auto scroll to top on page load
        },
        assetsPath: '../assets',
        globalPath: '../assets/global',
        layoutPath: '../assets/layouts/layout5',
        history: [],
        getCtrlRouter: function (name, ctrl, action) {
            return '/api.ashx?app=webapi&name=' + name + '&ctrl=' + ctrl + '&action=' + action;
        },

        getFileUrl: function (id) {
            return settings.getCtrlRouter("", "fileupload", "download") + "&id=" + id;
        },

        getViewUrl: function (view) {
            return "/apps/home/modules/" + view;
        },
        
        ///打开弹出框，如果ctrl无值，将按路由规则加载对应controller的js文件
        open: function (url, ctrl, data, ok, cancel,size) {
            url = url.toLowerCase().trimStringRight('.html');
            var resolve;
            if (!ctrl) {
                ctrl = url.replace(/\//g, '_') + '_controller';
                resolve = {
                    data: function () {
                        return data;
                    },
                    deps: ['$ocLazyLoad', function ($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'MainApp',
                            files: [
                                 Util.versionUrl("js/modules/" + url + '.js')
                            ]
                        });
                    }]
                };
            } else {
                resolve = {
                    data: function () {
                        return data;
                    }
                };
            }
            var modalInstance = $modal.open({
                templateUrl: settings.getViewUrl(url + '.html'),
                controller: ctrl,//app.controller(ctrl).controller,
                size: size || 'lg', backdrop: 'static',
                resolve: resolve
            });
            modalInstance.result.then(ok, cancel);

        },

        back: function () {
            if (settings.history.length > 0) {
                $location.path(settings.history.pop());
            } else {
                $location.path('/');
            }
        },
        showError: function (msg) {
            toastr.options = {
                closeButton: true,
                debug: false,
                positionClass: 'toast-top-right',
                onclick: null
            };
            toastr.error(msg);
        },
        post: function (path, args, success, error) {
            var url;
            if (path instanceof Array) {
                url = settings.getCtrlRouter(path[0], path[1], path[2]);
            } else {
                url = settings.getCtrlRouter(path.section, path.name, path.action);
            }
            $http.post(url, args).success(
            function (data, status, headers, config) {
                console.log("http post success. url:" + url + "| status:" + status + "| args:" + $filter("json")(args)); //+ "\r\n result:" + $filter("json")(data));
                if (data && data.ErrorMessage && data.ErrorStatus) {
                    if (error) {
                        error(data.ErrorMessage, data.ErrorStatus);
                    } else {
                        settings.showError(data.ErrorMessage);
                    }
                } else {
                    if (success) {
                        success(data, status, headers, config);
                    } else {
                        if (data.Result == 'true' || data.Result == true) {
                            settings.back();
                        } else {
                            settings.showError(data.Message);
                        }
                    }
                }
                
            }).error(function (data, status, headers, config) {
                if (error) {
                    error(data, status, headers, config);
                } else {
                    settings.showError(data);
                }
            });
        },
        postTest: function (path, args, success, error) {
            $timeout(function () { success({}); }, 0);
        },
        _dataSource : null,
        getDataSource: function () {
            if (!settings._dataSource) {
                settings._dataSource = new dataSource(settings);
            }
            return settings._dataSource;
        },
        //用户加载
        promises: [],
        /*
        * $scope : 视图页面的scope， 
        * ready：准备完成回调， 
        * waitView： 是否等待视图加载完成， 
        * waitLogin:是否等待用户完成登录并获取到用户信息
        */
        ready: function ($scope, ready, waitView, waitLogin) {
            if (waitView || !angular.isDefined(waitView)) {
                if (waitLogin || !angular.isDefined(waitLogin)) {
                    $q.all(settings.promises).then(function () {
                        ready();
                    });
                } else {
                    ready();
                }
            } else {
                if (waitLogin || !angular.isDefined(waitLogin)) {
                    $q.all(settings.promises).then(function () {
                        ready();
                    });
                } else {
                    ready();
                }
            }
        }

    };

    $rootScope.$on('$locationChangeSuccess', function (e, next, current) {
        var url = current.substring(current.indexOf('#') + 1);
        if (current != next) {
            settings.history.push(url);
        }
        if (url.indexOf('/list/data/form') == 0) {
            validator.setInvalidElementStyling(true);
        } else {
            validator.setInvalidElementStyling(false);
        }
    });

    $rootScope.settings = settings;

    return settings;
}]);


/* Setup Rounting For All Pages */
app.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
    function getControllerName(section,name,action) {
        if (section && name && action) {
            return section.toLowerCase() + "_" + name.toLowerCase() + "_" + action.toLowerCase() + "_controller";
        }
        if (section && name) {
            return section.toLowerCase() + "_" + name.toLowerCase() + "_controller";
        }
        throw "错误的controller控制器名称";
    }

    // Redirect any unmatched url
    $urlRouterProvider.otherwise("/");
    $urlRouterProvider.when('/home', '/');

    $stateProvider
    .state('home', {
        url: "/",
        templateUrl: "views/home.html",
        data: { pageTitle: '园所主页', pageSubTitle: '' },
        controller: "home_controller",
        resolve: {
            deps: ['$ocLazyLoad', function ($ocLazyLoad) {
                return $ocLazyLoad.load({
                    name: 'MainApp',
                    files: [
                         Util.versionUrl('modules/home.js')
                    ]
                });
            }]
        }
    })
    .state('common', {
        url: '/:section/:name',
        templateUrl: function ($stateParams) {
            return 'modules/' + $stateParams.section + '/' + $stateParams.name + '.html'
        },
        data: {},
        controllerProvider: function ($stateParams) {
            var ctrlName = getControllerName($stateParams.section, $stateParams.name);//$stateParams.section.toLowerCase() + "_" + $stateParams.name.toLowerCase() + "_controller";
            return ctrlName;
        },
        resolve: {
            deps: ['$ocLazyLoad', '$stateParams', function ($ocLazyLoad, $stateParams) {
                return $ocLazyLoad.load({
                    name: 'MainApp',
                    files: [
                         Util.versionUrl('modules/' + $stateParams.section + '/' + $stateParams.name + '.js')
                    ]
                });
            }]
        }
    })
    .state('common_action', {
        url: '/:section/:name/:action',
        templateUrl: function ($stateParams) {
            return 'modules/' + $stateParams.section + '/' + $stateParams.name + '/' + $stateParams.action + '.html'
        },
        data: {},
        controllerProvider: function ($stateParams) {
            var ctrlName = getControllerName($stateParams.section, $stateParams.name, $stateParams.action); //$stateParams.section.toLowerCase() + $stateParams.name.toLowerCase() + $stateParams.action.toLowerCase() + "controller";
            return ctrlName;
        },
        resolve: {
            deps: ['$ocLazyLoad', '$stateParams', function ($ocLazyLoad, $stateParams) {
                return $ocLazyLoad.load({
                    name: 'MainApp',
                    files: [
                         Util.versionUrl('modules/' + $stateParams.section + '/' + $stateParams.name + '/' + $stateParams.action + '.js')
                    ]
                });
            }]
        }
    })
    .state('common_action_id', {
        url: '/:section/:name/:action/:id',
        templateUrl: function ($stateParams) {
            return 'modules/' + $stateParams.section + '/' + $stateParams.name + '/' + $stateParams.action + '.html'
        },
        data: {},
        controllerProvider: function ($stateParams) {
            var ctrlName = getControllerName($stateParams.section, $stateParams.name, $stateParams.action); //$stateParams.section.toLowerCase() + $stateParams.name.toLowerCase() + $stateParams.action.toLowerCase() + "controller";
            return ctrlName;
        },
        resolve: {
            deps: ['$ocLazyLoad', '$stateParams', function ($ocLazyLoad, $stateParams) {
                return $ocLazyLoad.load({
                    name: 'MainApp',
                    files: [
                         Util.versionUrl('modules/' + $stateParams.section + '/' + $stateParams.name + '/' + $stateParams.action + '.js')
                    ]
                });
            }]
        }
    })
}]);

/* Setup App Main Controller */
app.controller('AppController', ['$scope', '$rootScope', '$http', '$location', '$state', '$q', function ($scope, $rootScope, $http, $location, $state, $q) {
    moment.locale('zh-cn');
    $scope.$on('$viewContentLoaded', function () {
        App.initComponents();
    });
}]);

/***
Layout Partials.
By default the partials are loaded through AngularJS ng-include directive. In case they loaded in server side(e.g: PHP include function) then below partial 
initialization can be disabled and Layout.init() should be called on page load complete as explained above.
***/

/* Setup Layout Part - Header */
app.controller('HeaderController', ['$rootScope', '$scope', '$http', function ($rootScope, $scope, $http) {
    $scope.$on('$includeContentLoaded', function() {
        Layout.initHeader(); // init header
    });    
}]);

app.controller('PageHeadController', ['$scope', function ($scope) {
    
}]);

app.controller('SidebarController', ['$scope', function ($scope) {
    $scope.$on('$includeContentLoaded', function () {
        QuickSidebar.init();
    });
}]);

/* Setup Layout Part - Footer */
app.controller('FooterController', ['$scope', function ($scope) {
    $scope.$on('$includeContentLoaded', function() {
        Layout.initFooter(); // init footer
    });
}]);

/**$http paramSerializer 实现
用于对异步加载html模板，控制器js时自动加版本标识后缀，解决浏览器缓存更新问题。
*/
app.factory("csParamSerializer", ["$httpParamSerializer", function ($httpParamSerializer) {
    var version = Util.version;////版本实际取自web.config配置信息
    var cachedUrls = ['tpl/', 'templates/', './templates/', 'js/', 'views/', '/apps/school']; ////这些路径下的js，html请求增加版本标识
    var addVersionParam = function (params) {
        if (!params) {
            params = { _v_: version };
        } else if (!params._v_) {
            params._v_ = version;
        }
        return params;
    };
    return function csParamSerializer(params) {
        var addedVersionParam = false;
        if (!this.cache && (this.method === 'GET' || this.method === 'JSONP')) {
            params = addVersionParam(params);
            addedVersionParam = true;
        }
        else {
            if(this.url){
                for (var i = 0; i < cachedUrls.length; i++) {
                    var cachedUrl = cachedUrls[i];
                    if (this.url.toLowerCase().indexOf(cachedUrl) === 0) {
                        params = addVersionParam(params);
                        addedVersionParam = true;
                        break;
                    }
                }
            }
        }
        //console.error(this.url);
        if (!addedVersionParam) {
            //console.warn("no url:" + this.url);
        }
        var result = $httpParamSerializer(params);
        
        return result;
    };
}]);


app.run(["$rootScope", "settings", "$state", '$q', 'defaultErrorMessageResolver', 'bootstrap3ElementModifier', 'validator', 'ecList', 'fieldSettings', '$http', function ($rootScope, settings, $state, $q, defaultErrorMessageResolver, bootstrap3ElementModifier, validator, ecList, fieldSettings, $http) {
    $http.defaults.paramSerializer = "csParamSerializer"; ////异步请求html，js时自动加版本标识的处理服务

    $rootScope.$state = $state; // state to be accessed from view
    $rootScope.$settings = settings; // state to be accessed from view
    
    
    defaultErrorMessageResolver.setI18nFileRootPath('../../../assets/global/plugins/angularjs/plugins/angular-auto-validate/lang');
    defaultErrorMessageResolver.setCulture('zh-CN');
    defaultErrorMessageResolver.setCulture('zh-CN', function () {
        var defer = $q.defer();
        // you can get the error messages however you want and resolve the promise when they are loaded
        // defer.resolve(errorMessagesRetreivedBySomeMethod);
        return defer.promise;
    });
    bootstrap3ElementModifier.enableValidationStateIcons(false);
    validator.setValidElementStyling(false);
    //修改自动验证代码添加的配置项
    validator.setEnableValidateSwitch(true);
    ecList.loadTemplate("../../../assets/global/plugins/angularjs/plugins/ec-list/ec-list.html").then(function () {

    });
    fieldSettings.loadTemplate("./templates/fields.html").then(function () {

    });


}]);